<template>
  <el-dialog
    :title="type == 'add' ? '添加配件展示商品' : '修改配件展示商品'"
    v-model="visible"
    @close="handleClose"
  >
    <el-form
      :model="ruleForm"
      :rules="rules"
      ref="formRef"
      class="good-form"
      label-width="120px"
    >
      <el-form-item label="排序值" prop="parts_id">
        <el-input
            v-model="ruleForm.parts_id"
            style="width: 60%"
            :readonly="isReadOnly"
        />
      </el-form-item>
      <el-form-item label="商品编号" prop="product_id">
        <el-input
            v-model="ruleForm.product_id"
            style="width: 60%"
            type="number"
        />
      </el-form-item>
      <el-form-item label="商品名称" prop="title">
        <el-input
            v-model="ruleForm.title"
            style="width: 60%"
        />
      </el-form-item>
      <el-form-item label="商品价格" prop="price">
        <el-input
            v-model="ruleForm.price"
            style="width: 60%"
            type="number"
        />
      </el-form-item>
      <el-form-item label="缩略图" prop="src">
        <el-upload
          ref="pictureUpload"
          name="img"
          class="avatar-uploader"
          accept="jpg,jpeg,png"
          list-type="picture-card"
          action="http://localhost/admin/upload"
          :limit="1"
          :auto-upload="true"
          :before-upload="handleBeforeUpload"
          :on-success="handleUrlSuccess"
          :on-change="handleChange"
        >
          <el-icon><Plus /></el-icon>
          <template #file="{ file }">
            <div>
              <img
                class="el-upload-list__item-thumbnail"
                :src="file.url"
                alt=""
              />
              <span class="el-upload-list__item-actions">
                <span
                  class="el-upload-list__item-delete"
                  @click="handleRemove(file)"
                >
                  <el-icon><Delete /></el-icon>
                </span>
              </span>
            </div>
          </template>
        </el-upload>
      </el-form-item>

      <el-form-item label="添加时间" prop="atime">
        <el-date-picker
          v-model="ruleForm.atime"
          type="datetime"
          placeholder="添加时间"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="visible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { getParts, addParts, updateParts } from "../../api/parts";

import {
  reactive,
  ref,
  toRefs,
  getCurrentInstance
} from "vue";

const props = defineProps({
  type: String,
});

const { proxy } = getCurrentInstance();
const pictureUpload = ref(null);
const isReadOnly = ref(false);
const formRef = ref(null);
const state = reactive({
  visible: false,
  ruleForm: {
    parts_id: "",
    product_id: "",
    title: "",
    price: "",
    src: "",
    atime: "",
  },
  rules: {
    parts_id: [{ required: true, message: "排序值不能为空", trigger: "change" }],
    product_id: [{ required: true, message: "商品编号不能为空", trigger: "change" }],
    title: [{ required: true, message: "商品名称不能为空", trigger: "change" }],
    price: [{ required: true, message: "商品价格不能为空", trigger: "change" }],
    src: [{ required: true, message: "图片不能为空", trigger: "change" }],
    atime: [{ required: true, message: "时间不能为空", trigger: "change" }]
  },
  id: ""
});

const { visible, ruleForm, rules, id } = toRefs(state);

const handleRemove = (file) => {
  pictureUpload.value.handleRemove(file);
};

const handleBeforeUpload = (file) => {
  const sufix = file.name.split(".")[1] || "";
  if (!["jpg", "jpeg", "png"].includes(sufix)) {
    ElMessage.error("请上传 jpg、jpeg、png 格式的图片");
    return false;
  }
};

const handleChange = (file) => {
  // console.log(file);
  state.ruleForm.src = file;
};

// 上传图片
const handleUrlSuccess = (val) => {
  // console.log(val);
  state.ruleForm.url = val.data || "";
};

// 开启弹窗
const open = (parts) => {
  // 开启弹窗
  state.visible = true;
  // 判断是添加还是修改
  if (parts) {
    // 修改
    let price = parts.price.replace(',','');
    state.ruleForm = {
      parts_id: parts.parts_id,
      product_id: parts.url,
      title: parts.title,
      price: price,
      src: parts.src,
      atime: parts.atime,
    };
    isReadOnly.value = true;
  } else {
    // 添加
    state.ruleForm = {
      parts_id: "",
      product_id: "",
      title: "",
      price: "",
      src: "",
      atime: "",
    };
    isReadOnly.value = false;
  }
};
// 关闭弹窗
const close = () => {
  state.visible = false;
};
const handleClose = () => {
  formRef.value.resetFields();
};

const emit = defineEmits(["changeTableData"]);

// 点击确定
const submitForm = () => {
  // 判断是添加还是修改
  if (!isReadOnly.value) {
    addParts(proxy, state.ruleForm).then((data) => {
      // console.log(data);
      if (data.code === 200) {
        getParts(proxy).then((result) => {
          emit("changeTableData", result);
        });
        ElMessage.success(data.msg);
      }else {
        ElMessage.warning(data.msg);
      }
    });
  } else {
    updateParts(proxy, state.ruleForm).then((data) => {
      if (data.code === 200) {
        getParts(proxy).then((result) => {
          emit("changeTableData", result);
        });
        ElMessage.success(data.msg);
      }else {
        ElMessage.warning(data.msg);
      }
    });
  }
  // 关闭弹窗
  state.visible = false;
};

// 因为使用 script setup的组件是默认关闭的，也即通过模板 ref 或者 $parent 链获取到的组件的公开实例，不会暴露任何在 script setup 中声明的绑定。
// 为了在 script setup 组件中明确要暴露出去的属性，使用 defineExpose 编译器宏：
defineExpose({
  open,
});
</script>

<style scoped>

</style>
